<template>
  <div>
    <div>
      <el-form :inline="true">
        <el-form-item>
          <el-input
              v-model="searchForm.username"
              placeholder="用户名"
              clearable
          >
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button @click="getUserList">搜索</el-button>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="dialogVisible = true" v-if="hasAuth('user:add')">新增
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-popconfirm title="这是确定批量删除吗？" @confirm="delHandle(null)">
            <template v-slot:reference>
              <el-button type="danger" :disabled="delBtlStatu" v-if="hasAuth('user:delete')">批量删除
              </el-button>
            </template>
          </el-popconfirm>
        </el-form-item>
      </el-form>
      <!--      展示用户列表-->
      <el-table
          fixed="left"
          ref="multipleTable"
          :data="tableData"
          tooltip-effect="dark"
          border
          stripe
          @selection-change="handleSelectionChange"
          @sort-change="handleTableSort">
        <el-table-column
            type="selection"
            width="40">
        </el-table-column>

        <el-table-column
            label="头像"
            width="50"
            height="80">
          <template v-slot:default="scope">
            <el-avatar size="small" :src="scope.row.avatar"></el-avatar>
          </template>
        </el-table-column>

        <el-table-column
            prop="username"
            label="用户名"
            width="150">
        </el-table-column>
        <el-table-column
            prop="nick_name"
            label="昵称"
            width="150">
        </el-table-column>
        <el-table-column
            sortable="custom"
            prop="gender"
            label="性别"
            width="80">
          <template v-slot:default="scope">
            <el-tag v-if="scope.row.gender===1">男</el-tag>
            <el-tag v-else-if="scope.row.gender===0">女</el-tag>
            <el-tag v-else-if="scope.row.gender===2">保密</el-tag>
          </template>
        </el-table-column>
        <el-table-column
            prop="roles"
            label="角色名称"
            width="120">
          <template v-slot:default="scope">
            <el-tag size="small" type="danger" v-for="item in scope.row.roles||''">{{ item.name }}</el-tag>
          </template>

        </el-table-column>
        <el-table-column
            prop="email"
            label="邮箱"
            width="120">
        </el-table-column>
        <el-table-column
            prop="phone"
            label="手机号"
            width="120">
        </el-table-column>

        <el-table-column
            prop="is_superuser"
            label="是否是超级管理员"
            sortable="custom"
        >
          <template v-slot:default="scope">
            <el-tag size="small" v-if="scope.row.is_superuser" type="success">是</el-tag>
            <el-tag size="small" v-else type="danger">否</el-tag>
          </template>

        </el-table-column>
        <el-table-column
            sortable="custom"
            prop="create_time"
            width="200"
            label="创建时间"
            show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
            fixed="right"
            prop="icon"
            width="300"
            label="操作">

          <template v-slot:default="scope">
            <el-button type="text" @click="roleHandle(scope.row.id)" v-if="hasAuth('user:role')">分配角色</el-button>
            <el-divider direction="vertical"></el-divider>

            <el-button type="text" @click="repassHandle(scope.row.id, scope.row.username)"
                       v-if="hasAuth('user:repass')">重置密码
            </el-button>
            <el-divider direction="vertical"></el-divider>

            <el-button type="text" @click="editHandle(scope.row.id)" v-if="hasAuth('user:update')">编辑</el-button>
            <el-divider direction="vertical"></el-divider>

            <template>
              <el-popconfirm title="这是一段内容确定删除吗？" @confirm="delHandle(scope.row.id)"
                             v-if="hasAuth('user:delete')">
                <template v-slot:reference>
                  <el-button type="text">删除</el-button>
                </template>
              </el-popconfirm>
            </template>

          </template>
        </el-table-column>

      </el-table>
      <!--分页器-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 50, 100]"
          :current-page="page"
          :page-size="size"
          :total="total">
      </el-pagination>


      <!--新增对话框-->
      <el-dialog :close-on-click-modal="false" :before-close="handleClose"
                 :visible.sync="dialogVisible" title="提示" width="570px">

        <el-form ref="editForm" :inline="true" :model="editForm" :rules="editFormRules" size="small" label-width="66px">
          <el-form-item label="用户名:" prop="username">
            <el-input v-model="editForm.username"/>
            <el-alert
                title="初始密码为:123456"
                :closable="false"
                type="info"
                style="line-height: 12px;"
            ></el-alert>
          </el-form-item>
          <el-form-item label="电话:" prop="phone">
            <el-input v-model.number="editForm.phone"/>
          </el-form-item>
          <el-form-item label="昵称:" prop="nickName">
            <el-input v-model="editForm.nick_name"/>
          </el-form-item>
          <el-form-item label="邮箱:" prop="email">
            <el-input v-model="editForm.email"/>
          </el-form-item>
          <el-form-item label="部门:" prop="position">
            <treeselect
                style="width: 170px"
                placeholder="选择部门"
                v-model="editForm.position"
                :options="deptData"
                :normalizer="normalizer"
            />
          </el-form-item>
          <el-form-item label="性别">
            <el-radio-group v-model="editForm.gender" style="width: 178px">
              <el-radio :label="1" border>男</el-radio>
              <el-radio :label="0" border>女</el-radio>
              <el-radio :label="2" border>保密</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="状态:" prop="is_show">
            <el-radio-group v-model="editForm.is_show">
              <el-radio :label="false" border>禁用</el-radio>
              <el-radio :label="true" border>启用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item style="margin-bottom: 0;" label="角色:" prop="roles">
            <el-select
                v-model="editForm.role"
                style="width: 437px"
                multiple
                placeholder="请选择"
            >
              <el-option
                  v-for="item in roleTreeData"
                  :key="item.name"
                  :label="item.name"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item style="margin-bottom: 0;" label="学校:" prop="school">
            <el-select
                v-model="editForm.school"
                style="width: 437px"
                placeholder="请选择">
              <el-option
                  v-for="item in schoolData"
                  :key="item.name"
                  :label="item.name"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="头像:" prop="avatar">
            <el-upload
                class="avatar-uploader"
                action=""
                :show-file-list="false"
                :before-upload="handleAvatar">
              <img v-if="editForm.avatar" :src="typeof editForm.avatar =='object'?uploadUrl:editForm.avatar"
                   class="avatar"
                   alt="图片加载失败">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="resetForm('editForm')">取消</el-button>
          <el-button type="primary" @click="submitForm('editForm')">确认</el-button>
        </div>
      </el-dialog>


      <!-- 分配权限对话框 -->
      <el-dialog title="分配角色" :visible.sync="roleDialogFormVisible" width="600px">
        <el-form :model="roleForm">
          <el-tree
              :data="roleTreeData"
              show-checkbox
              ref="roleTree"
              :check-strictly=checkStrictly
              node-key="id"
              :default-expand-all=true
              :props="defaultProps">
          </el-tree>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="roleDialogFormVisible=false">取 消</el-button>
          <el-button type="primary" @click="submitRoleHandle()">确 定</el-button>
        </div>
      </el-dialog>

    </div>
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {api} from "@/assets/static/js/settings";

function objectToFormData(obj) {
  if (typeof obj.avatar !== 'object') {
    // 如果传的不是文件对象，代表着是原来的图片
    delete obj.avatar
  }
  let formData = new FormData();
  Object.keys(obj).forEach(property => {
    if (Array.isArray(obj[property])) {
      // 如果是数组需要处理一下数据
      obj[property].forEach(item => {
        formData.append(property, item)
      })
    } else {
      formData.append(property, obj[property])
    }
  })
  return formData;
}

export default {
  name: "UserView",
  data() {
    return {
      userId: '',
      uploadUrl: '',
      // 搜索参数
      searchForm: {},
      // 总条数
      total: 0,
      // 搜索的size
      size: 10,
      // 页码
      page: 1,
      // 排序
      ordering: '',
      // 模态框是否可查看
      dialogVisible: false,
      // 分配角色模态框显示
      roleDialogFormVisible: false,
      // 提交的表单数据
      editForm: {
        // password: '',
        position: [],
        role: [],
      },
      // 提交方法
      submitMethod: '',
      tableData: [],
      schoolData: [],
      // 所有部门列表
      deptData: [],
      // 所有角色数据
      roleForm: {},
      roleTreeData: [],
      // 表单规则
      editFormRules: {
        username: [
          {required: true, message: '请输入用户名称', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'}
        ],
        is_show: [
          {required: true, message: '请选择状态', trigger: 'blur'}
        ],
        school: [
          {required: true, message: '请选择学校', trigger: 'blur'}
        ]
      },
      // 选择角色时 多选数据
      multipleSelection: [],
      // 删除按钮状态
      delBtlStatu: true,
      // 分配角色时的默认配置
      defaultProps: {
        children: 'roles',
        label: 'name'
      },
      treeCheckedKeys: [],
      checkStrictly: true,
    }
  },
  mounted() {
    // 获取用户列表
    this.getUserList()
    // 获取所有角色
    this.$axios.get(api.role).then(res => {
      if (res) {
        this.roleTreeData = res.results
      }
    })
    // 获取所有部门
    this.$axios.get(api.position_list).then(res => {
      if (res) {
        this.deptData = res.results
      }
    })
    // 获取所有学校
    this.$axios.get(api.school).then(res => {
      if (res) {
        this.schoolData = res.results
      }
    })
  },
  methods: {
    handleAvatar(file) {
      let avatar = new FileReader()
      avatar.readAsDataURL(file)
      avatar.onload = () => {
        this.$set(this.editForm, 'avatar', file)
        this.uploadUrl = avatar.result
        // console.log(this.editForm.avatar)
      }
      // 阻止上传
      return false
    },
    // vue-treeselect 配置label字段和children字段
    normalizer(node) {
      return {
        id: node.id,
        label: node.name,
        children: node.menus
      }
    },
    // 用户信息表排序监听事件
    handleTableSort(event) {
      // ascending 升序 descending 降序
      let order = event.order === 'ascending' ? '' : '-'
      this.ordering = order + event.prop
      this.getUserList()
    },
    // 处理多选数据
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.delBtlStatu = val.length === 0
    },
    // 分页器选择分页大小
    handleSizeChange(val) {
      this.size = val
      this.getUserList()
    },
    // 分页器选择页码
    handleCurrentChange(val) {
      this.page = val
      this.getUserList()
    },
    // 模态框点击取消按钮动作
    resetForm(formName) {
      this.dialogVisible = false
      this.editForm = {}
    },
    handleClose() {
      this.resetForm('editForm')
    },
    // 获取用户数据
    getUserList() {
      this.$axios.get(api.info, {
        params: {
          search: this.searchForm.username,
          page: this.page,
          size: this.size,
          ordering: this.ordering
        },
      }).then(res => {
        if (res) {
          this.tableData = res.results.results
          let user = this.$cookies.get('userInfo')
          this.tableData = this.tableData.filter(item => {
            // 排除当前用户
            return item.username !== user.username
          })
          this.total = res.results.count
        }
      })
    },
    // 提交表单动作
    submitForm(formName) {
      this.$refs.editForm.validate((valid) => {
        // 表单验证通过，进行提交操作
        if (valid) {
          console.log(this.editForm.id)
          let post_type = this.editForm.id ? this.$axios.put : this.$axios.post
          let formData = objectToFormData(this.editForm)
          post_type(api.info + (this.editForm.id ? this.editForm.id + '/' : ''), formData, {
            headers: {
              'content-type': 'multipart/form-data'
            }
          }).then(res => {
                if (res) {
                  this.$message({
                    showClose: true,
                    message: '恭喜你，操作成功',
                    type: 'success',
                    onClose: () => {
                      this.getUserList()
                    }
                  })
                  this.dialogVisible = false
                }
              }
          )
        } else {
          // 表单验证未通过
          console.log('Form validation failed');
          return false;
        }
      })
    },
    // 编辑单个用户信息
    editHandle(id) {
      // 获取单个用户信息
      this.$axios.get(api.info + id + '/').then(res => {
        if (res) {
          this.editForm = res.results
          this.dialogVisible = true
          this.submitMethod = 'put'
          this.userId = id
        }
      })
    },
    // 批量删除
    delHandle(id) {
      let ids = []
      if (id) {
        ids.push(id)
      } else {
        this.multipleSelection.forEach(row => {
          ids.push(row.id)
        })
      }
      this.$axios.post(api.batch_delete, {ids: ids}).then(res => {
            if (res) {
              this.$message({
                showClose: true,
                message: '恭喜你，操作成功',
                type: 'success',
                onClose: () => {
                  this.getUserList()
                }
              });
            }
          }
      )
    },
    // 修改角色
    roleHandle(id) {
      this.roleDialogFormVisible = true
      this.$axios.get(api.info + id + '/').then(res => {
        if (res) {
          this.roleForm = res.results
          let roleIds = []
          res.results.roles.forEach(row => {
            roleIds.push(row.id)
          })
          this.$refs.roleTree.setCheckedKeys(roleIds)
        }
      })
    },
    submitRoleHandle() {
      var roleIds = this.$refs.roleTree.getCheckedKeys()
      console.log(roleIds)
      this.$axios.put(api.info + this.roleForm.id + '/', {role: roleIds}).then(res => {
        if (res) {
          this.$message({
            showClose: true,
            message: '恭喜你，操作成功',
            type: 'success',
            onClose: () => {
              this.getUserList()
            }
          })
        }
      })
      this.roleDialogFormVisible = false
    },
    repassHandle(id, username) {
      this.$confirm('将重置用户【' + username + '】的密码, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.put(api.info + id + '/re_pass/').then(res => {
          if (res) {
            this.$message({
              showClose: true,
              message: '恭喜你，操作成功',
              type: 'success',
              onClose: () => {
              }
            });
          }
        })
      })
    },
    changeRole(value) {
      console.log(value)
    }
    ,
  },
  components: {
    Treeselect
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  line-height: 78px;
  text-align: center;
}

.avatar {
  width: 78px;
  height: 78px;
  display: block;
}
</style>